<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="成果名称" prop="cgName">
        <el-input
          v-model="queryParams.cgName"
          size="mini"
          placeholder="请输入成果名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目编号" prop="xmBh">
        <el-input
          v-model="queryParams.xmBh"
          size="mini"
          placeholder="请输入项目编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目归属" prop="xmGs">
        <el-select v-model="queryParams.xmGs" placeholder="请选择项目归属" clearable size="mini">
          <el-option
            v-for="dict in dict.type.kylx_ktgs"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请类别" prop="sqLb">
        <el-select v-model="queryParams.sqLb" placeholder="请选择申请类别" clearable size="mini">
          <el-option
            v-for="dict in dict.type.jdsq_sqlb"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['jdsq:jdsq:add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['jdsq:jdsq:edit']"
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['jdsq:jdsq:remove']"
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['jdsq:jdsq:export']"
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['jdsq:jdsq:import']"
          type="primary"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="!selectedRow || (selectedRow.processStatus !== 1 && selectedRow.processStatus !== 4)"
          @click="handleStartTask"
        >发起申请</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-delete"
          :disabled="!selectedRow || selectedRow.processStatus !== 2"
          @click="handleRevokeProcess"
        >撤销流程</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-delete"
          @click="handleExports"
        >导出docx</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 表格 -->
    <el-table
      ref="table"
      v-loading="loading"
      highlight-current-row
      :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
      :data="jdsqList"
      @row-click="clickRow"
      @selection-change="handleSelectionChange"
    >
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="申请年度" align="center" prop="sqNd" />
      <el-table-column label="项目编号" align="center" prop="xmBh" />
      <el-table-column label="成果名称" align="center" prop="cgName">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleButtonClick(scope.row)"
          >
            <el-link type="primary">{{ scope.row.cgName }}</el-link>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="申请鉴定单位" align="center" prop="sqJdDw">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.xmgl_lxwj_pzdw" :value="scope.row.sqJdDw" />
        </template>
      </el-table-column>
      <el-table-column label="申请鉴定时间" align="center" prop="sqJdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sqJdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="专业领域" align="center" prop="zyLy">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.kylx_ssly" :value="scope.row.zyLy" />
        </template>
      </el-table-column>
      <el-table-column label="经济效益(万元)" align="center" prop="jjXy" />
      <el-table-column label="项目负责人" align="center" prop="xmFzName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.processStatus==1 || scope.row.processStatus==4"
            v-hasPermi="['htbz:htbz:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.processStatus==1 || scope.row.processStatus==4"
            v-hasPermi="['htbz:htbz:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
          <el-button
            v-if="scope.row.processStatus !== 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleJinDu(scope.row)"
          >查询进度</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改鉴定申请对话框 -->
    <vxe-modal v-model="open" :title="title" width="80%" show-footer show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="110px">
        <el-tabs v-model="activeName" type="border-card">
          <!-- 成果基本资料 -->
          <el-tab-pane name="cgjbzl" :lazy="true">
            <span slot="label"><i class="el-icon-date" /> 成果基本资料</span>
            <div v-if="activeName === 'cgjbzl'" style="height: 70vh; overflow-y: auto;">
              <el-card shadow="never">
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="成果名称" prop="cgName">
                      <el-input v-model="form.cgName" placeholder="请输入成果名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目编号" prop="xmBh">
                      <!--                      <el-input v-model="form.xmBh" placeholder="请输入项目编号"/>-->
                      <el-input v-model="form.xmBh" disabled placeholder="请输入项目编号" @focus="selectKt">
                        <el-button slot="append" icon="el-icon-search" style="color: #1890ff" @click="selectKt">查询项目列表
                        </el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="项目归属" prop="xmGs">
                      <el-select v-model="form.xmGs" placeholder="请选择项目归属">
                        <el-option
                          v-for="dict in dict.type.kylx_ktgs"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="申请类别" prop="sqLb">
                      <el-select v-model="form.sqLb" placeholder="请选择申请类别">
                        <el-option
                          v-for="dict in dict.type.jdsq_sqlb"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="申请鉴定单位" prop="sqJdDw">
                      <el-input v-model="form.sqJdDw" placeholder="请输入申请鉴定单位" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="申请鉴定时间" prop="sqJdTime">
                      <el-date-picker
                        v-model="form.sqJdTime"
                        clearable
                        style="width: 100%;"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择申请鉴定时间"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="主要完成人" prop="zyWcr">
                      <el-input
                        v-model="form.zyWcr"
                        placeholder="请输入主要完成人"
                        :suffix-icon="'el-icon-search'"
                        @focus="selectUser(form.zyWcrId)"
                      />
                    </el-form-item>
                    <el-form-item v-if="1 === 2" label="主要完成人ID" prop="zyWcr">
                      <el-input v-model="form.zyWcrId" placeholder="请输入主要完成人Id" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="主要完成单位" prop="zyWcDw">
                      <el-select v-model="form.zyWcDw" placeholder="请输入主要完成单位">
                        <el-option
                          v-for="dict in dict.type.xmgl_lxwj_pzdw"
                          :key="dict.value"
                          :value="dict.value"
                        >
                          <span><i class="el-icon-office-building" /> {{ dict.label }}</span>
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="专业领域" prop="zyLy">
                      <el-select v-model="form.zyLy" placeholder="请选择专业领域">
                        <el-option
                          v-for="dict in dict.type.kylx_ssly"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="经济效益(万元)" prop="jjXy">
                      <el-input v-model="form.jjXy" placeholder="请输入经济效益(万元)" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="项目起时间" prop="xmQTime">
                      <el-date-picker
                        v-model="form.xmQTime"
                        clearable
                        style="width: 100%;"
                        type="month"
                        value-format="yyyy-MM"
                        placeholder="请选择项目起时间"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目止时间" prop="xmZTime">
                      <el-date-picker
                        v-model="form.xmZTime"
                        clearable
                        style="width: 100%;"
                        type="month"
                        value-format="yyyy-MM"
                        placeholder="请选择项目止时间"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="项目负责人" prop="xmFzName">
                      <el-input v-model="form.xmFzName" placeholder="请输入项目负责人" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系电话" prop="lxDh">
                      <el-input v-model="form.lxDh" placeholder="请输入联系电话" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="通讯地址" prop="txDz">
                  <el-input v-model="form.txDz" :rows="1" type="textarea" placeholder="请输入内容" />
                </el-form-item>
                <el-form-item v-if="1 === 2" label="申请年度" prop="sqNd">
                  <el-input v-model="form.sqNd" placeholder="请输入申请年度" />
                </el-form-item>
                <!--                    <el-form-item label="证书编号" prop="zsBh">-->
                <!--                      <el-input v-model="form.zsBh" placeholder="请输入证书编号"/>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item label="鉴定等级" prop="jdDj">-->
                <!--                      <el-input v-model="form.jdDj" placeholder="请输入鉴定等级"/>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item label="结题状态" prop="jtZt">-->
                <!--                      <el-input v-model="form.jtZt" placeholder="请输入结题状态"/>-->
                <!--                    </el-form-item>-->
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 研究人员名单 -->
          <el-tab-pane name="yjrymd" :lazy="true">
            <span slot="label"><i class="el-icon-date" /> 研究人员名单</span>
            <div v-if="activeName === 'yjrymd'" style="height: 70vh; overflow-y: auto;">
              <el-card class="box-card">
                <el-row :gutter="10" class="mb8">
                  <!--                  <el-col :span="1.5">-->
                  <!--                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddJdysJdsqYjry">添加</el-button>-->
                  <!--                  </el-col>-->
                  <el-col :span="1.5">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteJdysJdsqYjry">删除
                    </el-button>
                  </el-col>
                </el-row>
                <el-table
                  ref="jdysJdsqYjry"
                  height="60vh"
                  :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                  :data="jdysJdsqYjryList"
                  :row-class-name="rowJdysJdsqYjryIndex"
                  @selection-change="handleJdysJdsqYjrySelectionChange"
                >
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column label="序号" align="center" prop="index" width="50" />
                  <el-table-column show-overflow-tooltip label="姓名" align="center" prop="name" width="100" />
                  <el-table-column show-overflow-tooltip label="年龄" align="center" prop="age" width="70" />
                  <el-table-column show-overflow-tooltip label="职务" align="center" prop="zhiWu" />
                  <el-table-column show-overflow-tooltip label="职称" align="center" prop="zhiChen">
                    <template slot-scope="scope">
                      <dict-tag :options="dict.type.rcpt_zc" :value="scope.row.zhiChen" />
                    </template>
                  </el-table-column>
                  <el-table-column show-overflow-tooltip label="专业" align="center" prop="zy" />
                  <el-table-column show-overflow-tooltip label="本课题中分工" align="center" prop="bKtFg">
                    <!--                    <template slot-scope="scope">-->
                    <!--                      <el-input v-model="scope.row.bKtFg" placeholder="请输入本课题中分工"/>-->
                    <!--                    </template>-->
                  </el-table-column>
                  <el-table-column show-overflow-tooltip label="投入课题工作总月数" align="center" prop="trZys">
                    <!--                    <template slot-scope="scope">-->
                    <!--                      <el-input v-model="scope.row.trZys" placeholder="请输入投入课题工作总月数"/>-->
                    <!--                    </template>-->
                  </el-table-column>
                  <el-table-column show-overflow-tooltip label="工作单位" align="center" prop="gzDw" />
                </el-table>
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 技术资料目录 -->
          <el-tab-pane v-if="this.form.idWhere != null" name="jszlml" :lazy="true">
            <span slot="label"><i class="el-icon-date" /> 技术资料目录</span>
            <div v-if="activeName === 'jszlml'" style="height: 70vh; overflow-y: auto;">
              <el-card class="box-card">

                <el-row :gutter="20">
                  <el-col :span="4" :xs="24">
                    <div class="head-container">
                      <el-tree
                        ref="tree"
                        :data="fileOptions"
                        :props="defaultProps"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        node-key="id"
                        default-expand-all
                        highlight-current
                        :render-content="renderContent"
                        @node-click="handleNodeClick"
                      />
                    </div>
                  </el-col>
                  <el-col :span="20" :xs="24">
                    <el-row :gutter="10" class="mb8">
                      <el-col :span="1.5">
                        <!-- 上传按钮 -->
                        <el-button size="mini" icon="el-icon-upload" type="primary" @click="jdsqFjUpload">上传</el-button>
                      </el-col>
                      <el-col :span="1.5">
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteJdysJdsqFj">删除
                        </el-button>
                      </el-col>
                      <el-col :span="1.5">
                        <el-button type="success" icon="el-icon-download" sizi="mini" @click="handleDownloadAll">全部下载
                        </el-button>
                      </el-col>
                    </el-row>
                    <el-table
                      ref="jdysJdsqFj"
                      v-loading="loadingFj"
                      height="60vh"
                      :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                      :data="jdysJdsqFjList"
                      @selection-change="handleJdysJdsqFjSelectionChange"
                    >
                      <el-table-column type="selection" width="50" align="center" />
                      <el-table-column label="序号" align="center" type="index" width="50" />
                      <el-table-column label="附件类型" align="center" prop="fileType" />
                      <el-table-column label="文件名称" align="center" prop="fileName" :formatter="getFileNames" />
                      <el-table-column label="文件大小" align="center" prop="fileSize" />
                      <el-table-column label="操作" align="center" width="150">
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-download"
                            @click="handleDownload(scope.row)"
                          >下载
                          </el-button>
                          <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            @click="handlePreview(scope.row)"
                          >预览
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>

                  </el-col>
                </el-row>
              </el-card>
            </div>
          </el-tab-pane>

        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 鉴定申请导入 -->
    <JdSqDr ref="jdSqDr" />

    <!-- 课题选择 -->
    <HtXzKt ref="ktXz" />

    <!-- 多选科技人员 -->
    <KjryDuoXName ref="kjryDuoXName" @resSubmit="resSubmit" />

    <!-- 执行填报附件上传弹窗 -->
    <vxe-modal v-model="fjUpload" title="附件上传" width="25%" show-footer show-zoom resize @close="fjClose">
      <el-upload
        ref="fileUpload"
        align="center"
        class="upload-demo"
        multiple
        :action="uploadFileUrl"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="20"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :headers="headers"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">
          请上传
          <template> 大小不超过 <b style="color: #f56c6c">{{ 50 }}MB</b></template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
          的文件
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center;">
        <el-button v-if="allFilesUploaded === false" size="mini" type="primary" @click="fjUpload = false">关 闭
        </el-button>
        <el-button v-if="allFilesUploaded === true" size="mini" type="primary" @click="fjClose">上传完成, 关闭
        </el-button>
      </div>

    </vxe-modal>

    <!-- 查询进度 -->
    <Jindu ref="picture" />

    <!-- 鉴定申请详情 -->
    <JdSqXq ref="jdsqXq" />

    <!-- 预览组件 -->
    <KkFileView ref="preview" />
  </div>
</template>

<script>
import {
  addJdsq,
  delJdsq, delJdSqFj, exportJdsqWord,
  getJdsq,
  getJdSqId,
  insertJdsqFjByJdsqId,
  listJdsq,
  selectJdsqFjList,
  selectJdysJdsqYjryByJdsqId,
  updateJdsq
} from '@/api/xmgl/jdys/jdsq'
import JdSqDr from '@/views/xmgl/jdys/jdsq/components/JdSqDr'
import HtXzKt from '@/views/components/ktXz/HtXzKt'
import { selectLlglXmsbZcryByXmsbId } from '@/api/xmgl/lxgl/xmsb/xmsb'
import KjryDuoXName from '@/views/components/kjryXz/kjryDuoXName'
import { getToken } from '@/utils/auth'
import JSZip from 'jszip'
import Jindu from '@/views/components/liuChengState/jindu'
import { revokeProcess, startTask } from '@/api/activiti/task'
import JdSqXq from '@/views/xmgl/jdys/jdsq/components/JdSqXq'
import KkFileView from '@/views/components/KKFileView/kkFileView'

export default {
  name: 'Jdsq',
  components: { KkFileView, JdSqXq, Jindu, KjryDuoXName, HtXzKt, JdSqDr },
  dicts: ['xmgl_lxwj_pzdw', 'kylx_ktgs', 'jdsq_sqlb', 'kylx_ssly', 'rcpt_zc'],
  provide() {
    return {
      updateXmsbId: (val) => {
        this.form.cgName = val.ktName // 成果名称
        this.form.xmBh = val.ktBh // 项目编号
        this.form.xmGs = val.ktGs // 项目归属
        this.form.sqJdDw = val.zrBm // 申请鉴定单位
        this.form.xmQTime = val.qTime
        this.form.xmZTime = val.zTime
        this.form.xmFzName = val.fzName
        this.form.lxDh = val.fzPhone
        this.form.txDz = val.txdz
        this.form.zyLy = val.ssLy
        selectLlglXmsbZcryByXmsbId(val.xmsbId).then(res => {
          this.jdysJdsqYjryList = res.data.lxglXmsbZcryList
        })
      },
      // 赋值给 主要完成人
      updateKtZcRyLabel: (val) => {
        // 使用 map() 方法遍历数组中的每个对象，并提取出 name 属性
        const names = val.map(item => item.name)
        const ids = val.map(item => item.kjryId)

        // 使用 join() 方法将名字数组转换为逗号分隔的字符串
        this.form.zyWcr = names.join(',')
        this.form.zyWcrId = ids.join(',')
        this.$refs['formDialog'].validateField('zyWcr') // formDialog 是表单的 ref，zyWcr 是要验证的字段名
      }

    }
  },
  data() {
    return {
      jdsqFileType: '技术成果报告', // 默认的附件类型
      defaultProps: { children: 'children', label: 'label' }, // 表单参数
      fileOptions: [{ // 附件类型树表
        id: 1,
        label: '技术成果报告'
      }, {
        id: 2,
        label: '综合证明材料',
        children: [{
          id: 3,
          label: '查新检索报告书'
        }, {
          id: 4,
          label: '应用证明'
        }, {
          id: 5,
          label: '经济效益证明'
        }, {
          id: 6,
          label: '知识产权'
        }, {
          id: 7,
          label: '已获奖励'
        }, {
          id: 8,
          label: '发表论文'
        }, {
          id: 9,
          label: '申请表及相关'
        }]
      }, {
        id: 10,
        label: '科技成果鉴定证书初稿'
      }, {
        id: 11,
        label: '科技成果鉴定证书终稿'
      }, {
        id: 12,
        label: '验收资料'
      }],
      xg: false, // 判断是新增还是修改 (false新增 true修改)
      allFilesUploaded: false, // 添加这个来追踪所有文件是否上传完成
      fjUpload: false, // 附件上传弹窗
      jdsqIdEdit: '', // 要修改的 鉴定id
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传文件服务器地址
      fileList: [],
      headers: { Authorization: 'Bearer ' + getToken() },
      number: 0,
      uploadList: [],
      fileType: ['doc', 'xls', 'ppt', 'txt', 'pdf', 'docx', 'zip'],
      selectedRow: null, // 保存当前选中的行
      getJdSqId: null, // 从后端获取的鉴定申请主键ID
      activeName: 'cgjbzl', // 初始打开的标签页
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedJdysJdsqFj: [],
      // 研究人员子表选中数据
      checkedJdysJdsqYjry: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 鉴定申请表格数据
      jdsqList: [],
      // 鉴定申请附件表格数据
      jdysJdsqFjList: [],
      // 研究人员名单表格数据
      jdysJdsqYjryList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cgName: null,
        xmBh: null,
        xmGs: null,
        sqLb: null,
        sqNd: null,
        zsBh: null,
        jdDj: null,
        jtZt: null,
        userId: this.$store.state.user.id,
        deptId: null
      },
      // 附件查询参数
      queryParamsFj: {
        pageNum: 1,
        pageSize: 100,
        jdsqId: null,
        fileType: null,
        fileName: null,
        fileSize: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cgName: [{ required: true, message: '成果名称不能为空', trigger: 'blur' }],
        xmBh: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],
        xmGs: [{ required: true, message: '项目归属不能为空', trigger: 'change' }],
        sqLb: [{ required: true, message: '申请类别不能为空', trigger: 'change' }],
        sqJdDw: [{ required: true, message: '申请鉴定单位不能为空', trigger: 'change' }],
        sqJdTime: [{ required: true, message: '申请鉴定时间不能为空', trigger: 'blur' }],
        zyWcr: [{ required: true, message: '主要完成人不能为空', trigger: 'blur' }],
        zyLy: [{ required: true, message: '专业领域不能为空', trigger: 'change' }]
      },
      loadingFj: false

    }
  },
  watch: {
    activeName(newVal) {
      if (newVal === 'jszlml') {
        this.clickFirstNode()
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    if (this.activeName === 'jszlml') {
      this.clickFirstNode()
    }
  },
  methods: {
    resSubmit(ids) {
      console.log(ids)
      this.form.zyWcrId = ids
    },
    // 导出按钮操作
    handleExports() {
      const row = this.selectedRow // 获取当前选中的行
      const queryParams = this.queryParams
      const jdsqId = row.jdsqId
      this.$confirm('是否确认导出word文档?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        return exportJdsqWord(queryParams, jdsqId) // Passing userId to the exportWord function
      }).then(response => {
        // console.log('/profile/upload/' + response.msg)
        this.$download.resource('/profile/upload/' + response.msg)
        this.loading = false
      }).catch(() => {})
    },
    // 打开预览组件
    handlePreview(row) {
      this.$refs.preview.handleOpen(row)
    },
    // 打开鉴定申请详情
    handleButtonClick(row) {
      this.$refs.jdsqXq.handleOpen(row)
    },
    // 发起任务
    handleStartTask() {
      const row = this.selectedRow // 获取当前选中的行
      if (!row) {
        this.$message.error('请先选择一行数据')
        return
      }
      this.$confirm('是否确认发起申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          startTask({ businessKey: row.jdsqId, businessType: 8 }).then(res => {
            this.getList()
            this.$modal.msgSuccess('发起成功')
            this.selectedRow = null
          })
        })
        .catch(() => {})
    },
    // 撤销流程
    handleRevokeProcess() {
      const row = this.selectedRow // 获取当前选中的行
      if (!row) {
        this.$message.error('请先选择一行数据')
        return
      }
      this.$confirm('是否确撤销申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const params = {
            businessKey: row.jdsqId,
            businessType: 8,
            processInstanceId: row.processInstanceId
          }
          revokeProcess(params).then(res => {
            this.getList()
            this.$modal.msgSuccess('撤销成功')
            this.selectedRow = null
          })
        })
        .catch(() => {})
    },
    // 查询进度
    handleJinDu(row) {
      this.$refs.picture.handleOpen(row)
    },
    // 附件打包下载
    async handleDownloadAll() {
      const zip = new JSZip()

      getJdsq(this.jdsqIdEdit).then(async res => {
        const fileList = res.data.jdysJdsqFjList
        if (fileList.length === 0) {
          this.$modal.alertWarning('没有相关附件, 请先上传文件')
        } else {
          // 打开遮罩层
          this.$modal.loading('正在打包文件，请稍后...')
          for (let i = 0; i < fileList.length; i++) {
            const file = fileList[i]
            const fileName = file.fileName
            const finalFileName = fileName.substring(fileName.lastIndexOf('/') + 1)

            const fileResponse = await fetch(`/dev-api${fileName}`)
            const blob = await fileResponse.blob()
            zip.file(finalFileName, blob)
          }
          const content = await zip.generateAsync({ type: 'blob' })
          saveAs(content, `${res.data.cgName}_(附件).zip`)
          this.$modal.closeLoading()// 关闭遮罩层
        }
      })
    },
    clickFirstNode() {
      this.$nextTick(() => {
        const firstNode = this.$refs.tree.store.nodesMap['1'] // 默认点击id为1的节点
        if (firstNode) {
          this.$refs.tree.setCurrentKey(firstNode.key)
          this.handleNodeClicks(firstNode.data)
        }
      })
    },
    handleNodeClicks(data) {
      this.loadingFj = true
      this.jctbFileType = data.type
      this.queryParamsFj.fileType = this.jdsqFileType
      selectJdsqFjList(this.queryParamsFj).then(resFileList => {
        this.jdysJdsqFjList = resFileList.rows
        this.loadingFj = false
      })
    },
    // 节点单击事件
    handleNodeClick(data, node) {
      this.loadingFj = true
      if (node.level > 0 && node.data.children && node.data.children.length > 0) { // 检查是否有子节点
        const firstChildNode = node.data.children[0] // 获取第一个子节点
        this.$refs.tree.setCurrentKey(firstChildNode.id) // 设置当前选中的节点为第一个子节点
        data = firstChildNode // 更新 data 为第一个子节点的数据
        this.jdsqFileType = data.label
        this.queryParamsFj.fileType = this.jdsqFileType
        selectJdsqFjList(this.queryParamsFj).then(resFileList => {
          this.jdysJdsqFjList = resFileList.rows
          this.loadingFj = false
        })
      } else {
        // 根据附件类型查询附件列表
        this.jdsqFileType = data.label
        this.queryParamsFj.fileType = this.jdsqFileType
        selectJdsqFjList(this.queryParamsFj).then(resFileList => {
          this.jdysJdsqFjList = resFileList.rows
          this.loadingFj = false
        })
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 文件下载处理
    handleDownload(row) {
      const resource = row.fileName
      // 默认方法
      this.$download.resource(resource)
    },
    // 获取文件名原名
    getFileNames(row) {
      // 从路径中提取文件名
      return row.fileName.split('/').pop() // 返回文件名部分
    },
    // 关闭上传附件弹窗后
    fjClose() {
      this.fileList = []
      this.allFilesUploaded = false
      this.fjUpload = false
    },
    // 上传文件之前的钩子
    handleBeforeUpload(file) {
      const that = this
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.')
        const fileExt = fileName[fileName.length - 1]
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join('/')}格式文件!`)
          return false
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`)
            return false
          }
        }
        this.$modal.loading('正在上传文件，请稍候...')
        this.number++
        return true
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = ''
      separator = separator || ','
      for (const i in list) {
        strs += list[i].url + separator
      }
      return strs !== '' ? strs.substr(0, strs.length - 1) : ''
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError('上传文件失败，请重试')
      this.$modal.closeLoading()
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`)
    },
    // 上传成功
    handleUploadSuccess(res, file) {
      const that = this
      if (res.code === 200) {
        this.uploadList.push({ name: res.fileName, url: res.fileName, size: that.formatFileSize(file.size) })
        const xzItemFile = {
          'jdsqId': that.getJdSqId,
          'fileType': that.jdsqFileType,
          'fileName': res.fileName,
          'fileSize': that.formatFileSize(file.size)
        }
        const xgItemFile = {
          'jdsqId': that.jdsqIdEdit,
          'fileType': that.jdsqFileType,
          'fileName': res.fileName,
          'fileSize': that.formatFileSize(file.size)
        }
        if (this.xg === false) {
          // 点击新增按钮的上传
          insertJdsqFjByJdsqId(xzItemFile).then(resFil => {
            that.getJdsqFjList()
          })
        } else if (this.xg === true) {
          // 点击修改按钮的上传
          insertJdsqFjByJdsqId(xgItemFile).then(resFil => {
            that.getJdsqFjList()
          })
        }
        this.uploadedSuccessfully()
      } else {
        this.number--
        this.$modal.closeLoading()
        this.$modal.msgError(res.msg)
        this.$refs.fileUpload.handleRemove(file)
        this.uploadedSuccessfully()
      }
      this.allFilesUploaded = true
      this.$modal.msgSuccess('上传成功')
      // this.fjShangChuan = false
    },
    getJdsqFjList() {
      const that = this
      if (this.xg === false) {
        // 点击新增 上传文件后的文件列表
        this.queryParamsFj.jdsqId = that.getJdSqId
        this.queryParamsFj.fileType = this.jdsqFileType
        selectJdsqFjList(this.queryParamsFj).then(resFileList => {
          that.jdysJdsqFjList = resFileList.rows
        })
      } else {
        // 点击修改 上传文件后的文件列表
        this.queryParamsFj.jdsqId = that.jdsqIdEdit
        this.queryParamsFj.fileType = this.jdsqFileType
        selectJdsqFjList(this.queryParamsFj).then(resFileList => {
          that.jdysJdsqFjList = resFileList.rows
        })
      }
    },
    // 显示文件大小为KB, MB, GB, TB
    formatFileSize(size) {
      if (size === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(size) / Math.log(k))
      return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf('/') > -1) {
        return name.slice(name.lastIndexOf('/') + 1)
      } else {
        return name
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList)
        this.fileList = this.fileList.map(item => {
          // 使用replace方法去除name中的特定前缀
          item.name = item.name.split('/').pop()
          return item
        })
        this.uploadList = []
        this.number = 0
        this.$emit('input', this.listToString(this.fileList))
        this.$modal.closeLoading()
      }
    },
    jdsqFjUpload() { // 鉴定申请附件上传按钮
      this.fjUpload = true
    },
    clickRow(row) {
      this.selectedRow = row // 更新选中的行
      const table = this.$refs.table
      const selectedRows = table.selection

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow)
      })
      table.toggleRowSelection(row)
    },
    // 打开科技人员多选组件(科技人员姓名)(张三,李四,王五,赵六)
    selectUser(kjryId) {
      this.$refs.kjryDuoXName.handleOpen(kjryId)
    },
    // 打开选择课题弹窗
    selectKt() {
      this.$refs.ktXz.handleOpen()
    },
    /** 查询鉴定申请列表 */
    getList() {
      this.loading = true
      listJdsq(this.queryParams).then(response => {
        this.jdsqList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        jdsqId: this.getJdSqId,
        idWhere: null,
        cgName: null,
        xmBh: null,
        xmGs: null,
        sqLb: null,
        sqJdDw: null,
        sqJdTime: this.getCurrentDate(),
        zyWcr: null,
        zyWcrId: null,
        zyWcDw: null,
        zyLy: null,
        jjXy: null,
        xmQTime: null,
        xmZTime: null,
        xmFzName: null,
        lxDh: null,
        txDz: null,
        sqNd: new Date().getFullYear(),
        zsBh: null,
        jdDj: null,
        jtZt: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null
      }
      this.jdysJdsqFjList = []
      this.jdysJdsqYjryList = []
      this.resetForm('formDialog')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      const ids = selection.map(item => item.jdsqId)
      if (ids.length === 1) {
        this.ids = ids[0]
      } else {
        this.ids = ids
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      getJdSqId().then(res => {
        this.getJdSqId = res.msg
        this.reset()
      })
      this.activeName = 'cgjbzl'
      this.open = true
      this.title = '添加鉴定申请'
      this.selectKt()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      this.jdsqFileType = '技术成果报告'
      this.xg = true
      const jdsqId = row.jdsqId || this.ids
      this.jdsqIdEdit = row.jdsqId || this.ids
      getJdsq(jdsqId).then(response => {
        this.form = response.data

        this.queryParamsFj.jdsqId = jdsqId
        this.queryParamsFj.fileType = this.jdsqFileType
        selectJdsqFjList(this.queryParamsFj).then(resFileList => {
          this.jdysJdsqFjList = resFileList.rows
        })
        // this.jdysJdsqFjList = response.data.jdysJdsqFjList;
        selectJdysJdsqYjryByJdsqId(jdsqId).then(res => {
          this.jdysJdsqYjryList = res.data.jdysJdsqYjryList
        })
        this.activeName = 'cgjbzl'
        this.open = true
        this.title = '修改鉴定申请'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['formDialog'].validate(valid => {
        if (valid) {
          this.form.jdysJdsqFjList = this.jdysJdsqFjList
          this.form.jdysJdsqYjryList = this.jdysJdsqYjryList
          if (this.form.idWhere != null) { // 修改
            updateJdsq(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addJdsq(this.form).then(response => { // 新增
              this.$modal.msgSuccess('新增成功')
              // this.open = false;
              this.getList()
              this.handleUpdate(this.form)
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jdsqIds = row.jdsqId || this.ids
      this.$modal.confirm('确定删除选中记录？').then(function() {
        return delJdsq(jdsqIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 鉴定申请附件删除按钮操作 */
    handleDeleteJdysJdsqFj() {
      if (this.checkedJdysJdsqFj.length == 0) {
        this.$modal.msgError('请先选择要删除的鉴定申请附件数据')
      } else {
        const fjIds = this.checkedJdysJdsqFj
        this.$modal.confirm('确定删除选中记录？').then(function() {
          return delJdSqFj(fjIds)
        }).then(() => {
          this.queryParamsFj.jdsqId = this.jdsqIdEdit
          this.queryParamsFj.fileType = this.jdsqFileType
          selectJdsqFjList(this.queryParamsFj).then(resFileList => {
            this.jdysJdsqFjList = resFileList.rows
          })
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {})
      }
    },
    /** 复选框选中数据 */
    handleJdysJdsqFjSelectionChange(selection) {
      this.checkedJdysJdsqFj = selection.map(item => item.fjId)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jdsq/jdsq/export', {
        ...this.queryParams
      }, `jdsq_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('jdsq/jdsq/importTemplate', {}, `template_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.$refs.jdSqDr.handleImport()
    },
    /** 研究人员名单序号 */
    rowJdysJdsqYjryIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 研究人员名单添加按钮操作 */
    handleAddJdysJdsqYjry() {
      const obj = {}
      obj.name = ''
      obj.age = ''
      obj.zhiWu = ''
      obj.zhiChen = ''
      obj.zy = ''
      obj.bKtFg = ''
      obj.trZys = ''
      obj.gzDw = ''
      obj.jdsqId = ''
      this.jdysJdsqYjryList.push(obj)
    },
    /** 研究人员名单删除按钮操作 */
    handleDeleteJdysJdsqYjry() {
      if (this.checkedJdysJdsqYjry.length == 0) {
        this.$modal.msgError('请先选择要删除的研究人员名单数据')
      } else {
        const jdysJdsqYjryList = this.jdysJdsqYjryList
        const checkedJdysJdsqYjry = this.checkedJdysJdsqYjry
        this.jdysJdsqYjryList = jdysJdsqYjryList.filter(function(item) {
          return checkedJdysJdsqYjry.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleJdysJdsqYjrySelectionChange(selection) {
      this.checkedJdysJdsqYjry = selection.map(item => item.index)
    }

  }
}
</script>
